import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken, removeToken } from '@/utils/auth'

// create an axios instance
// 封装aioxs，自定义配置新建一个 axios 实例
const service = axios.create({
  // process.env 获取环境变量
  // VUE_APP_BASE_API  找配置环境变量1路径
  // baseURL: 'http://ihrm-java.itheima.net', // 设置axios请求的基础的基础地址
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// // 添加请求拦截器
// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 添加响应拦截器
// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data

    if (res.success) {
      Message({
        message: res.message || 'Error',
        type: 'success',
        duration: 5 * 1000
      })
      return res
    } else {
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  (error) => {
    console.dir('err' + error.response.data.code) // for debug
    // 判断token过期
    if (error.response.data.code === 10002) {
      removeToken()
      store.commit('user/RESET_STATE')
      router.push('/login')
      window.location.reload() // 实时刷新
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
